import { invoke } from "@tauri-apps/api/tauri";
import { UnlistenFn } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";

export async function sendMessage(message: string) {
  // naming convention: tauri-plugin-xxxx => plugin:xxxx
  await invoke("plugin:libp2p-signal|send_message", { message });
}

export async function sendObject(message: object) {
  await sendMessage(JSON.stringify(message));
}

export async function sendObjectWithTimestamp(message: object) {
  let temp = Object.assign(message, { timestamp: Date.now() });
  await sendMessage(JSON.stringify(temp));
}

export async function subscribe(topic: string) {
  // naming convention: tauri-plugin-xxxx => plugin:xxxx
  await invoke("plugin:libp2p-signal|subscribe", { topic });
}

export async function unsubscribe(topic: string) {
  // naming convention: tauri-plugin-xxxx => plugin:xxxx
  await invoke("plugin:libp2p-signal|unsubscribe", { topic });
}

export function onMessage(cb: (message: string) => void): Promise<UnlistenFn> {
  // event names can only contain alphanumber and '-/:_'
  return appWindow.listen<string>(
    "plugin:libp2p-signal:got-message",
    (event) => {
      cb(event.payload);
    }
  );
}
